"""
插件调试工具
用于调试和测试插件的工具
"""

import asyncio
import logging
import json
import traceback
from typing import Dict, Any, Optional
from src.plugins.plugin_manager import UnifiedPluginManager


class PluginDebugger:
    """插件调试器"""
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.plugin_manager = UnifiedPluginManager()
    
    async def debug_plugin(self, plugin_name: str, test_data: Optional[Any] = None) -> Dict[str, Any]:
        """
        调试插件
        
        Args:
            plugin_name: 插件名称
            test_data: 测试数据
            
        Returns:
            调试结果
        """
        result = {
            "plugin_name": plugin_name,
            "success": False,
            "error": None,
            "execution_time": 0,
            "output": None,
            "logs": []
        }
        
        try:
            # 记录开始时间
            import time
            start_time = time.time()
            
            # 加载插件
            plugin_info = self.plugin_manager.registry.get_plugin(plugin_name)
            if not plugin_info:
                result["error"] = f"插件 {plugin_name} 未找到"
                return result
            
            plugin_type = plugin_info.get("type", "custom")
            
            # 根据插件类型加载
            if plugin_type == "mcp":
                await self.plugin_manager.load_mcp_plugin(plugin_name, plugin_info)
            else:
                await self.plugin_manager.load_custom_plugin(plugin_name, plugin_info)
            
            # 检查插件是否加载成功
            if plugin_name not in self.plugin_manager.loaded_plugins:
                result["error"] = f"插件 {plugin_name} 加载失败"
                return result
            
            # 获取插件实例
            plugin = self.plugin_manager.get_plugin(plugin_name)
            if not plugin:
                result["error"] = f"无法获取插件 {plugin_name} 实例"
                return result
            
            # 执行插件
            try:
                if hasattr(plugin, 'execute'):
                    output = await plugin.execute(test_data)
                elif hasattr(plugin, 'fetch_data'):
                    output = await plugin.fetch_data(test_data or {})
                elif hasattr(plugin, 'process'):
                    output = await plugin.process(test_data or [])
                else:
                    output = "插件没有可执行的方法"
                
                result["output"] = output
                result["success"] = True
                
            except Exception as e:
                result["error"] = f"执行插件时出错: {str(e)}"
                result["logs"].append(f"执行错误: {traceback.format_exc()}")
            
            # 记录执行时间
            result["execution_time"] = time.time() - start_time
            
        except Exception as e:
            result["error"] = f"调试插件时出错: {str(e)}"
            result["logs"].append(f"调试错误: {traceback.format_exc()}")
        
        return result
    
    async def test_plugin_lifecycle(self, plugin_name: str) -> Dict[str, Any]:
        """
        测试插件生命周期
        
        Args:
            plugin_name: 插件名称
            
        Returns:
            测试结果
        """
        result = {
            "plugin_name": plugin_name,
            "lifecycle_tests": {},
            "success": False,
            "error": None
        }
        
        try:
            # 加载插件
            plugin_info = self.plugin_manager.registry.get_plugin(plugin_name)
            if not plugin_info:
                result["error"] = f"插件 {plugin_name} 未找到"
                return result
            
            plugin_type = plugin_info.get("type", "custom")
            
            # 生命周期测试：加载
            result["lifecycle_tests"]["load"] = {
                "success": False,
                "error": None
            }
            
            try:
                if plugin_type == "mcp":
                    await self.plugin_manager.load_mcp_plugin(plugin_name, plugin_info)
                else:
                    await self.plugin_manager.load_custom_plugin(plugin_name, plugin_info)
                
                result["lifecycle_tests"]["load"]["success"] = plugin_name in self.plugin_manager.loaded_plugins
            except Exception as e:
                result["lifecycle_tests"]["load"]["error"] = str(e)
            
            # 生命周期测试：启动
            result["lifecycle_tests"]["start"] = {
                "success": False,
                "error": None
            }
            
            try:
                start_result = await self.plugin_manager.start_plugin(plugin_name)
                result["lifecycle_tests"]["start"]["success"] = start_result
            except Exception as e:
                result["lifecycle_tests"]["start"]["error"] = str(e)
            
            # 生命周期测试：停止
            result["lifecycle_tests"]["stop"] = {
                "success": False,
                "error": None
            }
            
            try:
                stop_result = await self.plugin_manager.stop_plugin(plugin_name)
                result["lifecycle_tests"]["stop"]["success"] = stop_result
            except Exception as e:
                result["lifecycle_tests"]["stop"]["error"] = str(e)
            
            # 生命周期测试：卸载
            result["lifecycle_tests"]["unload"] = {
                "success": False,
                "error": None
            }
            
            try:
                unload_result = await self.plugin_manager.unload_plugin(plugin_name)
                result["lifecycle_tests"]["unload"]["success"] = unload_result
            except Exception as e:
                result["lifecycle_tests"]["unload"]["error"] = str(e)
            
            # 检查整体成功状态
            all_tests_passed = all(
                test["success"] for test in result["lifecycle_tests"].values()
            )
            result["success"] = all_tests_passed
            
        except Exception as e:
            result["error"] = f"测试插件生命周期时出错: {str(e)}"
        
        return result
    
    def validate_plugin_config(self, plugin_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        验证插件配置
        
        Args:
            plugin_config: 插件配置
            
        Returns:
            验证结果
        """
        result = {
            "valid": True,
            "errors": [],
            "warnings": []
        }
        
        # 检查必需字段
        required_fields = ["name", "type"]
        for field in required_fields:
            if field not in plugin_config:
                result["valid"] = False
                result["errors"].append(f"缺少必需字段: {field}")
        
        # 检查类型
        if "type" in plugin_config:
            valid_types = ["mcp", "custom"]
            if plugin_config["type"] not in valid_types:
                result["valid"] = False
                result["errors"].append(f"无效的插件类型: {plugin_config['type']}, 有效类型: {valid_types}")
        
        # 检查自定义插件路径
        if plugin_config.get("type") == "custom" and "path" not in plugin_config:
            result["warnings"].append("自定义插件建议指定 path 字段")
        
        # 检查MCP插件URL
        if plugin_config.get("type") == "mcp" and "url" not in plugin_config:
            result["warnings"].append("MCP插件建议指定 url 字段")
        
        return result


async def main():
    """调试器主函数示例"""
    debugger = PluginDebugger()
    
    # 示例：调试一个插件
    # result = await debugger.debug_plugin("filesystem", {"action": "list", "path": "."})
    # print(json.dumps(result, ensure_ascii=False, indent=2))
    
    # 示例：测试插件生命周期
    # lifecycle_result = await debugger.test_plugin_lifecycle("filesystem")
    # print(json.dumps(lifecycle_result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    asyncio.run(main())